package dao;

import java.sql.SQLException;

import org.apache.log4j.Logger;

import com.mysql.jdbc.ResultSet;

public class WeightMatrixDao {
	
	private ConnectionDB c;
	
	private static Logger log = Logger.getLogger(WeightMatrixDao.class);
	
	public WeightMatrixDao()
	{
		c = new ConnectionDB();
	}
	
	
	public void insert(int idPara, String weights)
	{
		String [] poids = weights.split(" ");
				
		for(int i = 0 ; i < poids.length; i++)
		{
			String w = poids[i];
			
			
			//on ne stocke que 150 caracteres pour le poids
			if(!w.equals("0.0"))
			{	
				if(w.length() > 150)
					w = w.substring(0,149);
			
				c.ajouter("Insert into pondmatrix values ('"+ idPara + "', '"+ i +"', '" + w + "')");
				//log.debug("INSERTING "+w);
			}
			else
			{
				log.debug("0.0");
			}
		}		
	}
	
	public void insertOne(int idPara, int wordId, String w)
	{
		//on ne stocke que 150 caracteres pour le poids
		if(!w.equals("0.0"))
		{	
			if(w.length() > 150)
				w = w.substring(0,149);
			
			c.ajouter("Insert into pondmatrix values ('"+ idPara + "', '"+ wordId +"', '" + w + "')");
		}
	}
	
	public String[] getLineByPara(int idPara)
	{
		String[] result = new String[2];
		String buffer = "";
		
		ResultSet rs = c.rechercher("Select paraId, cellValue from pondmatrix where paraId = '" + idPara + "';");
		
		try {
			while(rs.next())
			{
				String currentVal = rs.getString("cellValue");
				buffer += currentVal + " ";				
			}
			
			result[0] = String.valueOf(idPara);
			result[1] = buffer;
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return result;
	}
	
	
	public String getPondByParaAndWord(int idPara, int idWord)
	{
		String result = "0.0";
		String buffer = "";
		
		ResultSet rs = c.rechercher("Select cellValue from pondmatrix where paraId = '" + idPara + "' and wordId = '"+idWord+"';");
		
		try {
			while(rs.next())
			{
				result = rs.getString("cellValue");
			}
		
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return result;
	}
	
	public void close()
	{
		c.fermer();
	}
	
	public static void main(String [] args)
	{
		WeightMatrixDao dao = new WeightMatrixDao();
		
		/*int id = 5;
		String weights = "0.0;0.134;1.545";
		dao.insert(id, weights);*/
		log.debug("test="+dao.getPondByParaAndWord(0, 57));
	}
}
